// 定义默认配置项
const defaults = {
    // 设置默认的请求方式
    method: "get"
}

class Axios {
    // 构造器函数
    constructor(instanceConfig) {
        // 增加实例属性defaults
        this.defaults = instanceConfig;
    }
    request(configOrUrl={},config={}){
        // 判断configOrUrl是否为字符串，如果为字符串那么该参数即是请求地址
        if(typeof configOrUrl === "string"){
            config.url = configOrUrl;
        }else{
            // 如果configOrUrl不是字符串，那么可以认为configOrUrl是配置对象。
            config = configOrUrl;
        }
        config = {
            ...this.defaults,
            ...config
        }
        // 设置请求方式
        config.method = (config.method || this.defaults.method).toLowerCase();
        const dispatchRequest = function(){
            return new Promise((resolve,reject)=>{
                const request = new XMLHttpRequest();
                request.responseType = "json";
                request.open(config.method,config.url);
                request.send();
                request.onload = function(){
                    if(request.status === 200){
                        resolve({
                            config,
                            data:request.response,
                            headers:request.getAllResponseHeaders(),
                            request,
                            status:request.status,
                            statusText:request.statusText
                        });
                    }else{
                        reject({
                            code:"ERR_BAD_REQUEST",
                            config,
                            message:"Request failed with status code "+request.status,
                            name:"AxiosError",
                            request,
                            response:request.response
                        })
                    }

                }
                request.onerror = function(){
                    reject({
                        code:"ERR_NETWORK",
                        config,
                        message:"Network Error",
                        name:"AxiosError",
                        request,
                        response:request.response
                    })
                }
            })
        }
        return dispatchRequest();
    }
}

function createInstance(defaultConfig) {
    // 创建一个Axios实例赋值给常量context;
    const context = new Axios(defaultConfig);
    // instance的本质：Axios.prototype.request(将该函数的this指向到了context)
    const instance = Axios.prototype.request.bind(context);

    // 将Axios实例context的实例属性作为instance的属性。
    for(let key in context){
        instance[key] = context[key];
    }


    return instance;
}

// 将createInstance 函数运行的结果赋值给常量axios;
// defaults是默认的配置项。
const axios = createInstance(defaults);
// 默认导出axios
export default axios;